<template>
  <p-modal
    :visible="visible"
    :title="title"
    :mask-closable="false"
    :destroy-on-close="true"
    width="400px"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <p-form-model
      ref="form"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 18 }"
      :model="form"
      :rules="rules"
    >
      <p-form-model-item label="模板名称" prop="name">
        <p-input v-model="form.name" placeholder="请输入" />
      </p-form-model-item>
    </p-form-model>
  </p-modal>
</template>

<script>
import { postSaveTemplate } from '@/api/plan.js';

const defaultForm = {
  name: '',
};
export default {
  props: {
    title: {
      type: String,
      default: '保存模板',
    },
    pageType: {
      type: String,
      default: 'BP',
    },
    visible: {
      type: Boolean,
      default: false,
    },
    value: {
      type: [String, Number],
      default: undefined,
    },
    salesOrganization: {
      type: String,
      default: '',
    },
    dataSource: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      form: {
        ...defaultForm,
      },
      rules: {
        name: [
          { required: true, message: '请输入模板名称！', trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    handleCancel() {
      this.form = { ...defaultForm };
      this.$emit('update:visible', false);
    },
    handleOk() {
      console.log(this.dataSource, 'dataSource');
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const data = this.dataSource.map((item) => {
            return {
              salesGroup: item.salesGroup?.key,
              salesGroupName: item.salesGroup?.label,
              responsibleId: item.responsibleId?.key,
              responsibleName: item.responsibleId?.label,
              kapmGroup: item.kapmGroup?.key,
              kapmGroupName: item.kapmGroup?.label,
              templateName: this.form.name,
              salesOrganization: this.salesOrganization,
              type: this.pageType,
            };
          });
          await postSaveTemplate(data);
          // this.$emit('change', this.form.name);
          this.$message.success('保存成功！');
          this.handleCancel();
        }
      });
    },
  },
};
</script>

